var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var _limitMenu = system.MENULIMIT.STOCK11;
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH+'stock/data/page';
var querysizeurl = config.BASEPATH+'stock/data/size_data';
var _height = $(parent).height()-278,_width = $(parent).width()-192;
var Utils = {
	doQueryDepot : function(){
		commonDia = $.dialog({
			title : '选择仓库',
			content : 'url:'+config.BASEPATH+'base/depot/to_list_dialog_bymodule',
			data : {multiselect:false,module:'stock'},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					$("#depot_code").val(selected.dp_code);
					$("#depot_name").val(selected.dp_name);
				}
			},
			cancel:true
		});
	},
	doQueryBrand : function(){
		commonDia = $.dialog({
			title : '选择品牌',
			content : 'url:'+config.BASEPATH+'base/brand/to_list_dialog',
			data : {multiselect:true},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var codes = [];
				var names = [];
				for(var i=0;i<selected.length;i++){
					codes.push(selected[i].bd_code);
					names.push(selected[i].bd_name);
				}
				$("#bd_code").val(codes.join(","));
				$("#bd_name").val(names.join(","));
			},
			close:function(){
			},
			cancel:true
		});
	},
	doQueryType : function(){
		commonDia = $.dialog({
			title : '选择类别',
			content : 'url:'+config.BASEPATH+'base/type/to_tree_dialog',
			data : {multiselect:true},
			width : 300,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var codes = [];
				var names = [];
				for(var i=0;i<selected.length;i++){
					codes.push(selected[i].tp_code);
					names.push(selected[i].tp_name);
				}
				$("#tp_code").val(codes.join(","));
				$("#tp_name").val(names.join(","));
			},
			close:function(){
			},
			cancel:true
		});
	},
	imports:function(){
		/*var myDate = new Date();
		var hours = myDate.getHours();//获取当前小时数(0-23)
		if(hours >7 && hours < 22){
			$.dialog.tips("大批量导入请在22点后进行操作！",3,"32X32/fail.png");
			return;
		}
		if (IsFinishInit == "1") {
			$.dialog.tips("已经启用帐套,不能导入数据！",2,"32X32/fail.png");
			return;
		}*/
		var depot_code = $("#depot_code").val();
    	if(depot_code == ""){
    		Public.tips({type: 2, content : "请选择仓库！"});
			return;
		}
		/*//只能修改自己店铺下的仓库
		var DI_SI_Code = $("#DI_SI_Code").val();//获取仓库所属店铺CODE
		var curr_si_code = $("#curr_si_code").val();
		if(curr_si_code != "001"){//如果为总部，跳过验证
			if(DI_SI_Code != curr_si_code){
				$.dialog.tips("对不起，您没有修改权限",2,"32X32/hits.png");
				return true;
			}
		}*/
		$.dialog({
			title : '库存批量导入',
			content : 'url:'+config.BASEPATH+"stock/data/to_import_stock?depot_code="+depot_code,
			data: {callback: this.callback},
			width : 550,
			height : 350,
			max : false,
			min : false,
			cache : false,
			lock: true
		});
	}
};

var handle = {
	operFmatter : function(val, opt, row){
		var btnHtml = '';
		if (row.et_ar_state == '0') {
            btnHtml += '<input type="button" value="审核" class="btn_sp" onclick="javascript:handle.operate(\'approve\',' + opt.rowId + ');" />';
        }else if (row.et_ar_state == '2') {
            btnHtml += '<input type="button" value="修改" class="btn_xg" onclick="javascript:handle.operate(\'edit\',' + opt.rowId + ');" />';
        }else if (row.et_ar_state == '1') {//审核通过
        	btnHtml += '<input type="button" value="查看" class="btn_ck" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');" />';
        } 
		return btnHtml;
	},
	formatArState:function(val, opt, row){//0：未审核；1：已审核2：已退回
		if(val == 0){
			return '未审核';
		}else if(val == 1){
			return '已审核';
		}else if(val == 2){
			return '已退回';
		}
		return val;
	}
};

/*获取尺码组信息后台*/

var sizeGroupList = null;
var sizeGroupMaxLength = 0;
function getSizeTitle(){
	$.ajax({
		type:"POST",
		async:false,
		url:config.BASEPATH+"stock/data/size_title?"+THISPAGE.buildParams(),
		dataType:"json",
		success:function(data){
			if(undefined != data && data.stat == 200){
				sizeGroupMaxLength=0;
				sizeGroupList=data.data;
				for(var key in sizeGroupList){
					var sizeGroup = sizeGroupList[key];
					if (sizeGroup != null && sizeGroup.length>sizeGroupMaxLength){
						sizeGroupMaxLength=sizeGroup.length;
					}
				}
			}
		}
	});
}

var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();	
	},
	initDom:function(){
		this.$_sizeMode = $("#sizeMode").cssCheckbox({callback:function($_obj){
			if($_obj.find("input")[0].checked){
				$("#listMode_Ul").hide();
				$("#list-grid").hide();
				$("#size-grid").show();
			}else{
				$("#listMode_Ul").show();
				$("#list-grid").show();
				$("#size-grid").hide();
			}
			$('#btn-search').click();
		}});
		this.$_showColor = $("#showColor").cssCheckbox({callback:function($_obj){
			if($_obj.find("input")[0].checked){
				$("#grid").showCol("cr_name");
			}else{
				$("#grid").hideCol("cr_name");
			}
			THISPAGE.reloadData();
		}});
		this.$_showSize = $("#showSize").cssCheckbox({callback:function($_obj){
			if($_obj.find("input")[0].checked){
				$("#grid").showCol("sz_name");
			}else{
				$("#grid").hideCol("sz_name");
			}
			THISPAGE.reloadData();
		}});
		this.$_showBra = $("#showBra").cssCheckbox({callback:function($_obj){
			if($_obj.find("input")[0].checked){
				$("#grid").showCol("br_name");
			}else{
				$("#grid").hideCol("br_name");
			}
			THISPAGE.reloadData();
		}});
		this.$_exactQuery = $("#exactQuery").cssCheckbox();
		this.initSeason();
		this.initYear();
		this.initZeroShow();
	},
	initSeason:function(){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+"base/dict/list?dtl_upcode=KEY_SEASON",
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.data != "" && data.data.length > 0){
					var seasons = data.data;
					seasons.unshift({dtl_code:"",dtl_name:"全部"});
					$('#span_pd_season').combo({
						value : 'dtl_code',
						text : 'dtl_name',
						width : 207,
						listHeight : 300,
						listId : '',
						defaultSelected : 0,
						editable : false,
						callback : {
							onChange : function(data) {
								if(data.dtl_code != ""){
									$("#pd_season").val(data.dtl_name);
								}else{
									$("#pd_season").val("");
								}
							}
						}
					}).getCombo().loadData(seasons,["dtl_name",$("#pd_season").val(),0]);
				}
			}
		 });
	},
	initYear:function(){
		var currentYear = new Date().getFullYear();
		var data = [
		    {Code:"",Name:"全部"},
			{Code:""+parseInt(currentYear+1)+"",Name:""+parseInt(currentYear+1)+""},
			{Code:""+parseInt(currentYear)+"",Name:""+parseInt(currentYear)+""},
			{Code:""+parseInt(currentYear-1)+"",Name:""+parseInt(currentYear-1)+""},
			{Code:""+parseInt(currentYear-2)+"",Name:""+parseInt(currentYear-2)+""},
			{Code:""+parseInt(currentYear-3)+"",Name:""+parseInt(currentYear-3)+""},
			{Code:""+parseInt(currentYear-4)+"",Name:""+parseInt(currentYear-4)+""},
			{Code:""+parseInt(currentYear-5)+"",Name:""+parseInt(currentYear-5)+""}
		];
		$('#span_pd_year').combo({
			data:data,
			value: 'Code',
			text: 'Name',
			width :206,
			height:80,
			listId:'',
			defaultSelected: 0,
			editable: false,
			callback:{
				onChange: function(data){
					$("#pd_year").val(data.Code);
				}
			}
		}).getCombo();
	},
	initZeroShow:function(){
		var data = [
		    {Code:"0",Name:"不显示为零的行"},
		    {Code:"1",Name:"显示为零的行"}
		];
		$('#span_showZero').combo({
			data:data,
			value: 'Code',
			text: 'Name',
			width :206,
			height:80,
			listId:'',
			defaultSelected: 0,
			editable: false,
			callback:{
				onChange: function(data){
					$("#showZero").val(data.Code);
				}
			}
		}).getCombo();
	},
	initGrid:function(){
		var colModel = [
//	    	{name: 'operate',label:'操作',width: 60, formatter: handle.operFmatter,align:'center', sortable:false},
	    	{label:'商品货号',name: 'pd_no',index: 'pd_no',width:100, fixed:true},
	    	{label:'商品名称',name: 'pd_name',index: 'pd_name',width:150, fixed:true},
	    	{label:'类别',name: 'tp_name',index: 'pd_tp_code',width:80},
	    	{label:'品牌',name: 'bd_name',index: 'pd_bd_code',width:80},
	    	{label:'上市时间',name: 'pd_date',index: 'pd_date',width:80},
	    	{label:'年份',name: 'pd_year',index: 'pd_year',width:60},
	    	{label:'季节',name: 'pd_season',index: 'pd_season',width:60},
	    	{label:'款式',name: 'pd_style',index: 'pd_style',width:60},
	    	{label:'面料',name: 'pd_fabric',index: 'pd_fabric',width:60},
	    	{label:'单位',name: 'pd_unit',index: 'pd_unit',width:60},
	    	{label:'颜色',name: 'cr_name',index: 'sd_cr_code',width:70,hidden:true},
	    	{label:'尺码',name: 'sz_name',index: 'sd_sz_code',width:70,hidden:true},
	    	{label:'杯型',name: 'br_name',index: 'sd_br_code',width:70,hidden:true},
	    	{label:'库存数量',name: 'sd_amount',index: 'sd_amount',width:70,align:"right"},
	    	{label:'成本价格',name: 'pd_cost_price',index: 'pd_cost_price',width:80,align:"right",sortable:false,formatter: PriceLimit.formatByCost},
	    	{label:'成本金额',name: 'cost_money',index: 'cost_money',width:80,align:"right",sortable:false,formatter: PriceLimit.formatByCost},
	    	{label:'零售价',name: 'pd_sell_price',index: 'pd_sell_price',width:80,align:"right",sortable:false,formatter: PriceLimit.formatBySell},
	    	{label:'零售金额',name: 'sell_money',index: 'sell_money',width:80,align:"right",sortable:false,formatter: PriceLimit.formatBySell}
	    ];
		$('#grid').jqGrid({
            url:queryurl+'?'+THISPAGE.buildParams(),			
			datatype: 'json',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:config.DATAROWNUM,//每页条数
			rowList:config.DATAROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			footerrow: true,
			userDataOnFooter: true,
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
                userdata: 'data.data',
				repeatitems : false,
				id: 'sd_id'  //图标ID
			},
			loadComplete: function(data){
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	initSizeGrid:function(){
		getSizeTitle();
		$("#sizeGrid").jqGrid('GridUnload');
		var colModel = [
	    	{label:'商品货号',name: 'pd_no',index: 'pd_no',width:100, fixed:true},
	    	{label:'商品名称',name: 'pd_name',index: 'pd_name',width:150, fixed:true},
	    	{label:'颜色',name: 'cr_name',index: 'sd_cr_code',width:70},
	    	{label:'杯型',name: 'br_name',index: 'sd_br_code',width:70},
	    	{label:'',name: 'pd_szg_code',index: 'pd_szg_code',width:70,hidden:true}
	    ];
		for (var i = 0; i < sizeGroupMaxLength; i++) {
			colModel.push({label:'-',name: "amountMap.size"+i,index:'',width: 60, title: false,sortable:false,align:'center'});
		}
		colModel = colModel.concat([
			{label:'库存数量',name: 'sd_amount',index: 'sd_amount',width:70,align:"right"},
			{label:'成本价格',name: 'pd_cost_price',index: 'pd_cost_price',width:80,align:"right",sortable:false,formatter: PriceLimit.formatByCost},
			{label:'成本金额',name: 'cost_money',index: 'cost_money',width:80,align:"right",sortable:false,formatter: PriceLimit.formatByCost},
			{label:'零售价',name: 'pd_sell_price',index: 'pd_sell_price',width:80,align:"right",sortable:false,formatter: PriceLimit.formatBySell},
			{label:'零售金额',name: 'sell_money',index: 'sell_money',width:80,align:"right",sortable:false,formatter: PriceLimit.formatBySell}
		]);
		$('#sizeGrid').jqGrid({
            url:querysizeurl+'?'+THISPAGE.buildParams(),			
			datatype: 'json',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#sizePage',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:config.DATAROWNUM,//每页条数
			rowList:config.DATAROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			footerrow: true,
			userDataOnFooter: true,
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
                userdata: 'data.data',
				repeatitems : false,
				id: 'sd_id'  //图标ID
			},
			onCellSelect:function(rowid){
				var rowData=$('#sizeGrid').getRowData(rowid);
				var sizeGroup = sizeGroupList[rowData.pd_szg_code];
				for (var i = 0; i < sizeGroup.length; i++) {
					$('#sizeGrid').setLabel("amountMap.size"+i,sizeGroup[i].sz_name);
				}
				for (var i = sizeGroup.length; i < sizeGroupMaxLength; i++) {
					$('#sizeGrid').setLabel("amountMap.size"+i,"-");
				}
			},
			loadComplete: function(data){
				$("#sizeGrid tr:eq(1)").trigger("click");
			},
			loadError: function(xhr, status, error){		
			}
	    });
		
	},
	buildParams : function(){
		var params = '';
		params += 'type='+$("#type").val();
		params += '&bd_code='+$("#bd_code").val();
		params += '&tp_code='+$("#tp_code").val();
		params += '&pd_season='+$("#pd_season").val();
		params += '&pd_year='+$("#pd_year").val();
		params += '&pd_no='+Public.encodeURI($("#pd_no").val());
		params += '&depot_code='+$("#depot_code").val();
		params += '&showZero='+$("#showZero").val();
		params += '&showColor='+(THISPAGE.$_showColor.chkVal().join()? 1 : 0);
		params += '&showSize='+(THISPAGE.$_showSize.chkVal().join()? 1 : 0);
		params += '&showBra='+(THISPAGE.$_showBra.chkVal().join()? 1 : 0);
		params += '&exactQuery='+(THISPAGE.$_exactQuery.chkVal().join()? 1 : 0);
		return params;
	},
	reset:function(){
		$("#pd_no").val("");
		$("#bd_name").val("");
		$("#bd_code").val("");
		$("#tp_name").val("");
		$("#tp_code").val("");
		$("#span_pd_season").getCombo().selectByValue("");
		$("#span_pd_year").getCombo().selectByValue("");
		$("#depot_name").val("");
		$("#depot_code").val("");
	},
	reloadData:function(){
		var param=THISPAGE.buildParams();
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+'?'+param}).trigger("reloadGrid");
	},
	initEvent:function(){
		$('#pd_no').on('keyup',function(event){
			if (event.keyCode==13){
				$('#btn-search').click();
			}
		});
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			var sizeMode = THISPAGE.$_sizeMode.chkVal().join();
			if(sizeMode){
				THISPAGE.initSizeGrid();
			}else{
				THISPAGE.reloadData();
			}
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			Public.hideConstion();
			THISPAGE.reloadData();
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
		$('#btn-import').on('click', function(e){
			e.preventDefault();
			/*if (!Business.verifyRight(_limitMenu,_menuParam.IMPORT)) {
				return ;
			};*/
			Utils.imports();
		});
	}
}
THISPAGE.init();